package com.example.demo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

@WebServlet(name = "userregServlet", value = "/userregServlet")
public class userregServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.查看前端发送的请求数据  request
        //2.执行程序逻辑xxxx
        //3、返回结果到前端 response
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        //1、查看登陆参数 用户名和密码
        String txtStuno = request.getParameter("txtStuno");
        String txtStupwd = request.getParameter("txtStupwd");
        String txtStuname = request.getParameter("txtStuname");
        String txtStubirthday = request.getParameter("txtStubirthday");
        // 数据库连接URL，格式为：jdbc:mysql://host:port/databaseName
        String url = "jdbc:mysql://localhost:3306/user";
        String user = "root";    // 数据库用户名
        String password = "12345";// 数据库密码
        int a =0;int result =0;
        try {
            // 加载MySQL JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection conn = DriverManager.getConnection(url, user, password);
            // 创建Statement对象执行SQL语句
            Statement stmt = conn.createStatement();
            String sql="insert into users2(userNo,userPwd,userName,birthday) VALUES('"+txtStuno+"','"+txtStupwd
                    +"','"+txtStuname+"','"+txtStubirthday+"')";
            //insert delete update stmt.executeUpdate(sql);
            //select  stmt.executeQuery(sql)
            a = stmt.executeUpdate(sql);
            // 关闭结果集、Statement和连接
            //rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.执行登陆逻辑
        //3.返回登陆结果
        if (a == 1 )
            //response.getWriter().println("注册成功.");
            response.sendRedirect("userlogin.html");
        else
            response.getWriter().println("注册失败.");
        // System.out.println("xxxxxxxxxxxxxxxxxx do post");
    }
}
